package peer.p2pnet.message;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.UnknownHostException;

import peer.Message;
import peer.p2pnet.DBNodeIdent;
import peer.tools.ByteIntSwitch;
import peer.tools.ByteShortSwitch;
import peer.tools.Mdb;
import server.Group;

public class DBSynMessage2 extends Message{
	public short sType=peer.tools.MessageType.sType_DBSynMessage2;
	Mdb mdb;
	int eventOffset;
	int eventOffset2;
	byte[] dpData;
	short eventByteLength;
	DBNodeIdent[] joinDBNode;
	DBNodeIdent[] quitDBNode;
	public DBSynMessage2(Mdb mdb,int eventOffset2){
		this.mdb=mdb;
		this.eventOffset2=eventOffset2;
		Group group=server.Config.groupMange.getGroup(mdb);
		byte[] eventByte=group.getMemberChangeEventByte(eventOffset2);
		dpData=new byte[4+eventByte.length];		
		eventByteLength=(short) eventByte.length;
		ByteShortSwitch.toByteArray(ver, dpData, 0);  //add: ver
		ByteShortSwitch.toByteArray(sType, dpData, 2);  //add: service type
		System.arraycopy(eventByte, 0, dpData, 4, eventByte.length);
		dp=new DatagramPacket(dpData,dpData.length);
	}
	
	public DBSynMessage2(DatagramPacket dp) throws UnknownHostException {
		this.dp=dp;
		dpData=dp.getData();
		ver=ByteShortSwitch.toShort(dpData, 0);
		sType=ByteShortSwitch.toShort(dpData, 2);
		
		int offset=4;
		eventOffset=ByteIntSwitch.toInt(dpData, 4);
		//System.out.println("QQQeventOffset   "+eventOffset);
		offset+=4;
		int joinDBNum=dpData[offset];
		offset+=1;
		joinDBNode=new DBNodeIdent[joinDBNum];
		//System.out.println("AAAAAAAAA   "+joinDBNum);
		for(int i=0;i<joinDBNum;i++){
			byte[] ipb=new byte[4];
			System.arraycopy(dpData, offset, ipb, 0, 4);
			InetAddress ip=InetAddress.getByAddress(ipb);
			offset+=4;
			int port=peer.tools.ByteIntSwitch.toInt(dpData, offset);
			joinDBNode[i]=new DBNodeIdent(ip,port);
			offset+=4;
		}
		
		int quitDBNum=dpData[offset];
		offset+=1;
		quitDBNode=new DBNodeIdent[quitDBNum];
		//System.out.println("BBBBBBBBB "+quitDBNum);
		for(int i=0;i<quitDBNum;i++){
			byte[] ipb=new byte[4];
			System.arraycopy(dpData, offset, ipb, 0, 4);
			InetAddress ip=InetAddress.getByAddress(ipb);
			offset+=4;
			int port=peer.tools.ByteIntSwitch.toInt(dpData, offset);
			quitDBNode[i]=new DBNodeIdent(ip,port);
			offset+=4;
			//System.out.println("eee "+ip+port);
		}
	}
	
	public DBNodeIdent[] getJoinDBNode(){
		return joinDBNode;
	}
	
	public DBNodeIdent[] getQuitDBNode(){
		return quitDBNode;
	}
	
	public int getEventOffset(){
		return eventOffset;
	}
}
